package com.sumainfor.wx.tenant.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用阿里云识身份证的工具类
 */
public class AlibabaOCR {


    public Map<String, Object> getIdendo(Map<String, String> params) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String host = "https://cardiddecode.market.alicloudapi.com/api/decode_cardid_aliyun";
            String appcode = "c8a411a9ba8642cf8353f289558fa505";
            if (params.get("imgbase64") != null) {

                String img = params.get("imgbase64").toString();

                String bodys = "{\"imgbase64\":\"" + img + "\"}";

                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, bodys);

                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                Response response = HttpUtil.doPostForOCR(host, body).execute();
                if (!response.isSuccessful()) {
                    result.put("code", 400);
                    result.put("msg", "服务器繁忙...");
                    return result;
                }
                //System.out.println(response.toString());
                //获取response的body
                String str = response.body().string();
                response.close();
                Map<String, Object> map = JSONObject.parseObject(str,Map.class);
                if (map.get("code").toString().equals("200")) {

                    result.put("code", 0);
                    result.put("data", map.get("data"));
                } else {

                    result.put("code", 400);
                    result.put("msg", map.get("desc"));
                }

            } else {

                result.put("code", 400);
                result.put("msg", "请输入必传参数");
            }

        } catch (Exception e) {
            result.put("code", 400);
            result.put("msg", "服务器繁忙...");

        }
        return result;
    }


    public static void main(String[] args) throws Exception {
        Map<String,String> rasmap = new HashMap<String, String>();

        String  uel ="iVBOA2f6Wu/7h53dPcd3b/B2J";
        rasmap.put("imgbase64",uel);
       Map<String,Object> map=  new  AlibabaOCR().getIdendo(rasmap);
        System.err.println(map);
    }

}
